//
//  LSContactSelectViewController.m
//  LaSaCivilAffairsDepartment
//
//  Created by 聂志康 on 2019/8/22.
//  Copyright © 2019 wpkj. All rights reserved.
//

#import "LSContactSelectViewController.h"
#import "LSContactSelectTableViewModel.h"
#import "LSContactSelectTableViewCell.h"
#define SelectViewWidth (147/3*2)
#define SelectViewHeight 100
#define headerSearchViewHeight 103
#define CountPerPage 1000

@interface LSContactSelectViewController () <UITableViewDelegate, UITableViewDataSource, LSContactSelectTableViewCellDelegate>
@property (nonatomic, strong) UITextField *nameTF;
@property (nonatomic, strong) UITextField *departmentTF;
@property (nonatomic, copy) didFinishSelectBlock block;
@property (nonatomic, copy) didFinishChooseBlock singleBlock;
@property (nonatomic, strong) LSContactSelectTableViewModel *selectedModel;
@property (nonatomic, strong) NSMutableArray *dataArrM;
@property (nonatomic, strong) NSMutableArray *selectedArrayM;
@property (nonatomic, strong) UITableView *allTableView;
@property (nonatomic, assign) int tableViewPage;
@end

static NSString *LSContactSelectTableViewCellID = @"LSContactSelectTableViewCellID";

@implementation LSContactSelectViewController

- (instancetype)initWithSelectedArray:(NSArray *)selectedArray andCompleteHandler:(didFinishSelectBlock)hander {
    self = [super init];
    if (self) {
        _block = hander;
        _selectedArrayM = selectedArray.mutableCopy;
    }
    return self;
}

- (instancetype)initWithCompleteHandler:(didFinishChooseBlock)hander {
    self = [super init];
    if (self) {
        _singleBlock = hander;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"用户列表";
    UIButton *confirmButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 44)];
    [confirmButton setTitle:@"确定" forState:UIControlStateNormal];
    [confirmButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    confirmButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [confirmButton addTarget:self action:@selector(confirmButtonClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *confirmButtonItem = [[UIBarButtonItem alloc] initWithCustomView:confirmButton];
    self.navigationItem.rightBarButtonItem = confirmButtonItem;
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    [backButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backButtonClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = backButtonItem;
    [self setUpHeaderSearchView];
    [self.view addSubview:self.allTableView];
    _allTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    [self loadData];
}

- (void)backButtonClick {
    [self dismissViewControllerAnimated:true completion:nil];
}

- (void)confirmButtonClick {
    if (_singleBlock) {
        if (!_selectedModel) {
            [MBProgressHUD showTipMessageInWindow:@"请选择"];
            return;
        }
        self.singleBlock(_selectedModel);
        [self backButtonClick];
    } else if (_block) {
        if (self.selectedArrayM.count <= 0) {
            [MBProgressHUD showTipMessageInWindow:@"请选择"];
            return;
        }
        self.block(self.selectedArrayM.copy);
        [self backButtonClick];
    }
}

- (void)setUpHeaderSearchView {
    UIView *headerSearchView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, headerSearchViewHeight)];
    headerSearchView.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:headerSearchView];
    UIView *headerViewBottomLineView = [[UIView alloc] initWithFrame:CGRectMake(0, headerSearchViewHeight-0.5, ScreenWidth, 0.5)];
    headerViewBottomLineView.backgroundColor = hexColor(CCCCCC);
    [headerSearchView addSubview:headerViewBottomLineView];
    
    // 拟文名
    UITextField *nameTF = [[UITextField alloc] initWithFrame:CGRectMake(15, 5+4, (ScreenWidth-30), 36)];
    self.nameTF = nameTF;
    nameTF.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:12];
    nameTF.layer.borderColor = hexColor(dbdbdb).CGColor;
    nameTF.layer.borderWidth = 1;
    nameTF.returnKeyType = UIReturnKeySearch;
    nameTF.placeholder = @"请输入姓名";
    nameTF.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 8, 1)];
    nameTF.leftViewMode = UITextFieldViewModeAlways;
    [headerSearchView addSubview:nameTF];
    
    
    UITextField *departmentTF = [[UITextField alloc] initWithFrame:CGRectMake(15, 54+4, ScreenWidth-30-55-15, 36)];
    self.departmentTF = departmentTF;
    departmentTF.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:12];
    departmentTF.layer.borderColor = hexColor(dbdbdb).CGColor;
    departmentTF.layer.borderWidth = 1;
    departmentTF.returnKeyType = UIReturnKeySearch;
    departmentTF.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    departmentTF.placeholder = @"请输入部门";
    departmentTF.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 8, 1)];
    departmentTF.leftViewMode = UITextFieldViewModeAlways;
    [headerSearchView addSubview:departmentTF];
    
    UIButton *searchButton = [[UIButton alloc] initWithFrame:CGRectMake(ScreenWidth-15-55, 54+4, 55, 36)];
    searchButton.layer.cornerRadius = 4;
    searchButton.layer.masksToBounds = true;
    searchButton.backgroundColor = NAV_COLOR;
    [searchButton setTitle:@"搜索" forState:UIControlStateNormal];
    searchButton.titleLabel.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:12];
    [searchButton addTarget:self action:@selector(loadData) forControlEvents:UIControlEventTouchUpInside];
    [headerSearchView addSubview:searchButton];
}

- (void)checkIfModelIsSelected:(LSContactSelectTableViewModel *)model {
    for (LSContactSelectTableViewModel *subModel in self.selectedArrayM) {
        if ([subModel.username isEqualToString:model.username]) {
            model.isSelected = true;
        }
    }
}

- (void)loadData {
    [self.view endEditing:YES];
    self.tableViewPage = 1;
    NSDictionary *param = @{@"token":[ValidateUtils validateNull:[UserInfoModel sharedInstance].token],@"rows":[NSString stringWithFormat:@"%d",CountPerPage],@"page":[NSString stringWithFormat:@"%d",self.tableViewPage],@"realname":[self.nameTF.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]],@"departname":[self.departmentTF.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]};
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:true];
    [NetworkUtils requestNOHandleWithMethod:@"POST" URL:yZPageUser param:param completionHandler:^(id responseObject, NSError *connectionError) {
        [hud hideAnimated:true];
        self.allTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        [self.allTableView.mj_header endRefreshing];
        if (!connectionError) {
             [self.dataArrM removeAllObjects];
            NSArray *dataArray = [responseObject objectForKey:@"data"];
            if (dataArray && dataArray.count > 0) {
                if (dataArray.count < self.tableViewPage*CountPerPage) {
                    [self.allTableView.mj_footer endRefreshingWithNoMoreData];
                }
                for (NSDictionary *subDic in dataArray) {
                    LSContactSelectTableViewModel *model = [LSContactSelectTableViewModel mj_objectWithKeyValues:subDic];
                    [self checkIfModelIsSelected:model];
                    [self.dataArrM addObject:model];
                }
            }else{
                 [self.allTableView.mj_footer endRefreshingWithNoMoreData];
            }
             [self.allTableView reloadData];
        } else {
            [MBProgressHUD showTipMessageInWindow:connectionError.localizedDescription];
        }
    }];
}

- (void)loadMoreData {
    self.tableViewPage++;
    NSDictionary *param = @{@"token":[ValidateUtils validateNull:[UserInfoModel sharedInstance].token],@"rows":[NSString stringWithFormat:@"%d",CountPerPage],@"page":[NSString stringWithFormat:@"%d",self.tableViewPage],@"realname":self.nameTF.text,@"departname":self.departmentTF.text};
    [NetworkUtils requestNOHandleWithMethod:@"POST" URL:yZPageUser param:param completionHandler:^(id responseObject, NSError *connectionError) {
        if (!connectionError) {
            NSArray *dataArray = [responseObject objectForKey:@"data"];
            if (dataArray && dataArray.count > 0) {
                for (NSDictionary *subDic in dataArray) {
                    LSContactSelectTableViewModel *model = [LSContactSelectTableViewModel mj_objectWithKeyValues:subDic];
                    [self checkIfModelIsSelected:model];
                    [self.dataArrM addObject:model];
                }
                if (self.dataArrM.count < self.tableViewPage*CountPerPage) {
                    [self.allTableView.mj_footer endRefreshingWithNoMoreData];
                } else {
                    [self.allTableView.mj_footer endRefreshing];
                }
                [self.allTableView reloadData];
            } else {
                self.tableViewPage--;
                [self.allTableView.mj_footer endRefreshingWithNoMoreData];
            }
        } else {
            self.tableViewPage--;
            [self.allTableView.mj_footer endRefreshing];
            [MBProgressHUD showTipMessageInWindow:connectionError.localizedDescription];
        }
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArrM.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LSContactSelectTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:LSContactSelectTableViewCellID forIndexPath:indexPath];
    cell.delegate = self;
    LSContactSelectTableViewModel *model=self.dataArrM[indexPath.row];
    cell.model = model;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:true];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return LSContactSelectTableViewCellHeight;
}

- (UITableView *)allTableView {
    if (!_allTableView) {
        _allTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, headerSearchViewHeight, ScreenWidth, ScreenHeight-SafeAreaTopHeight-headerSearchViewHeight)];
        _allTableView.delegate = self;
        _allTableView.dataSource = self;
        _allTableView.backgroundColor = hexColor(F0F0F0);
        _allTableView.tableFooterView = [UIView new];
        _allTableView.separatorInset = UIEdgeInsetsZero;
        [_allTableView registerClass:LSContactSelectTableViewCell.class forCellReuseIdentifier:LSContactSelectTableViewCellID];
    }
    return _allTableView;
}

#pragma mark - LSContactSelectTableViewCellDelegate
- (void)selectButtonDidClick:(LSContactSelectTableViewModel *)model {
    if (_singleBlock) {
        if (model.isSelected) {
            self.selectedModel.isSelected = false;
            self.selectedModel = model;
        }
        [self.allTableView reloadData];
    } else {
        if (model.isSelected) {
            [self.selectedArrayM addObject:model];
        } else {
            [self.selectedArrayM removeObject:model];
        }
    }
}

- (NSMutableArray *)dataArrM {
    if (!_dataArrM) {
        _dataArrM = [[NSMutableArray alloc] init];
    }
    return _dataArrM;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
